package com.yangye.pisecurity.controller;

import com.yangye.picommon.enums.PiResultEnum;
import com.yangye.picommon.model.PiResult;
import com.yangye.picommon.utils.JwtTokenUtil;
import com.yangye.pisecurity.model.LoginRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangye
 * @date 2019/9/24
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@PostMapping("/login")
	PiResult login(@RequestBody LoginRequest loginRequest) {
		if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
			return PiResult.fail(PiResultEnum.BAD_USERNAME_PASSWORD);
		}
		Authentication authentication = authenticationManager.
				authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
		SecurityContextHolder.getContext()
				.setAuthentication(authentication);

		// 生成jwt token
		UserDetails user = (UserDetails) authentication.getPrincipal();
		String token = jwtTokenUtil.generateToken(user);
		Map<String, String> tokenMap = new HashMap<String, String>();
		tokenMap.put("token", token);
		return PiResult.succeed(tokenMap);
	}

	@PostMapping("/logout")
	PiResult logout() {
		return PiResult.succeed();
	}
}
